package com.sxjh.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.extra.cglib.CglibUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxjh.common.ZPage;
import com.sxjh.entity.Task;
import com.sxjh.entity.UnloadLog;
import com.sxjh.entity.param.UnloadLogDayParam;
import com.sxjh.entity.param.UnloadLogListParam;
import com.sxjh.entity.param.UnloadLogWeighParam;
import com.sxjh.entity.result.IcWagonNumberResult;
import com.sxjh.entity.result.UnloadLogDayResult;
import com.sxjh.entity.result.UnloadLogListResult;
import com.sxjh.entity.result.UnloadLogWeighResult;
import com.sxjh.mapper.UnloadLogMapper;
import com.sxjh.service.UnloadLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 卸货记录  服务实现类
 * </p>
 *
 * @author zixin
 * @since 2021-06-06
 */
@Slf4j
@Service
public class UnloadLogServiceImpl extends ServiceImpl<UnloadLogMapper, UnloadLog> implements UnloadLogService {

    @Resource
    private UnloadLogMapper unloadLogMapper;

    @Override
    public ZPage<UnloadLogListResult> page(UnloadLogListParam param) {
        Page<UnloadLogListResult> iPage = new Page<>(param.getCurrent(), param.getSize());
        QueryWrapper<UnloadLogListResult> queryWrapper = this.queryFilter(param);
        IPage<UnloadLogListResult> resultPage = unloadLogMapper.page(iPage, queryWrapper);
        return new ZPage(resultPage);
    }

    @Override
    public List<UnloadLogListResult> details(UnloadLogListParam param) {
        Page<UnloadLogListResult> iPage = new Page<>(1, -1);
        QueryWrapper<UnloadLogListResult> queryWrapper = this.queryFilter(param);
        IPage<UnloadLogListResult> resultPage = unloadLogMapper.page(iPage, queryWrapper);
        return resultPage.getRecords();
    }

    /**
     * 卸货列表 数据处理
     */
    @Override
    public List<UnloadLogListResult> list(UnloadLogListParam param) {
        List<UnloadLogListResult> list = unloadLogMapper.list(param);
        List<UnloadLogListResult> results = new ArrayList<>();
        // 小计
        UnloadLogListResult subtotal = new UnloadLogListResult();
        subtotal.setVehNumber("小计");
        subtotal.setTare("0");
        subtotal.setRough("0");
        subtotal.setNetWeight("0");
        // 合计
        UnloadLogListResult total = new UnloadLogListResult();
        total.setVehNumber("合计");
        total.setTare("0");
        total.setRough("0");
        total.setNetWeight("0");
        // 车号
        String vehNumber = null;
        // 物料
        String materialName = null;
        if (CollUtil.isNotEmpty(list)) {
            vehNumber = list.get(0).getVehNumber();
            materialName = list.get(0).getMaterialName();
        }
        int count = 0; // 统计小计的车数
        int countSum = 0; // 合计车数export
        for (UnloadLogListResult item : list) {
            countSum++;
            // 处理净重量
            BigDecimal bigDecimal = new BigDecimal(item.getRough()).subtract(new BigDecimal(item.getTare()));
            item.setNetWeight(bigDecimal.toString());
            // 小计计算完成
            if (!vehNumber.equals(item.getVehNumber()) || !materialName.equals(item.getMaterialName())) {
                // 更新车号，物料记录
                subtotal.setVehNumber("小计（" + count + "）");
                vehNumber = item.getVehNumber();
                materialName = item.getMaterialName();
                UnloadLogListResult temp = CglibUtil.copy(subtotal, UnloadLogListResult.class);
                results.add(temp);
                // 重新计小计
                subtotal.setTare("0");
                subtotal.setRough("0");
                subtotal.setNetWeight("0");
                count = 0;
            }
            count++;
            results.add(item);
            // 计算小计
            subtotal.setTare(new BigDecimal(subtotal.getTare()).add(new BigDecimal(item.getTare())).toString());
            subtotal.setRough(new BigDecimal(subtotal.getRough()).add(new BigDecimal(item.getRough())).toString());
            subtotal.setNetWeight(new BigDecimal(subtotal.getNetWeight()).add(new BigDecimal(item.getNetWeight())).toString());
            // 数据添入合计
            total.setTare(new BigDecimal(total.getTare()).add(new BigDecimal(item.getTare())).toString());
            total.setRough(new BigDecimal(total.getRough()).add(new BigDecimal(item.getRough())).toString());
            total.setNetWeight(new BigDecimal(total.getNetWeight()).add(new BigDecimal(item.getNetWeight())).toString());
        }
        subtotal.setVehNumber("小计" + "（" + count + "）");
        total.setVehNumber("合计" + "（" + countSum + "）");
        results.add(subtotal);
        results.add(total);
        return results;
    }

    @Override
    public List<UnloadLogDayResult> day(UnloadLogDayParam param) {
        List<UnloadLogDayResult> list = unloadLogMapper.day(param);
        // 合计
        UnloadLogDayResult total = new UnloadLogDayResult();
        total.setMaterialName("合计");
        total.setRough(new BigDecimal(0));
        total.setTare(new BigDecimal(0));
        total.setNetWeight(new BigDecimal(0));
        total.setVehCount(0);

        BigDecimal netTotal = new BigDecimal(0);
        for (UnloadLogDayResult item : list) {
            // 处理净重量
            if (item.getRough() != null) {
                item.setNetWeight(item.getRough()
                        .subtract(item.getTare())
                        .setScale(2, BigDecimal.ROUND_HALF_UP));
                // 处理负值问题
                BigDecimal netWeight = item.getNetWeight();
                netWeight = netWeight != null && netWeight.doubleValue() > 0 ? netWeight : null;
                item.setNetWeight(netWeight);
            }
            // 格式化字段
            if (item.getRough() != null) {
                item.setRough(item.getRough().setScale(2, BigDecimal.ROUND_HALF_UP));
            }
            item.setTare(item.getTare().setScale(2, BigDecimal.ROUND_HALF_UP));
            // 数据添入合计
            total.setTare(total.getTare().add(item.getTare()));
            if (item.getRough() != null) {
                total.setRough(total.getRough().add(item.getRough()));
            }
            if (item.getNetWeight() != null) {
                netTotal = total.getNetWeight().add(item.getNetWeight());
            }
            total.setVehCount(total.getVehCount() + item.getVehCount());
            total.setNetWeight(netTotal);
        }

        list.add(total);
        return list;
    }

    public static void main(String[] args) {
        BigDecimal b = new BigDecimal(0);
        for (int i = 0; i < 5; i++) {
             b = b.add(new BigDecimal(5));
        }
        System.out.println(b);
    }

    // 生成流水号
    @Override
    public String serial() {
        LocalDate localDate = LocalDate.now();
        String number = "DY" + LocalDateTimeUtil.format(localDate, "YYYYMMdd");
        Integer serial = unloadLogMapper.serial(LocalDate.now());
        serial++;
        if (serial.toString().length() == 1) {
            number += "00" + serial;
        }
        if (serial.toString().length() == 2) {
            number += "0" + serial;
        }
        return number;
    }

    @Override
    public UnloadLogWeighResult getPrint(String number) {
        return unloadLogMapper.getPrint(number);
    }

    @Override
    public String getSerives(int wagonNumberId) {
        List<UnloadLog> unloadLogList = list(
                new LambdaQueryWrapper<UnloadLog>()
                        .eq(UnloadLog::getWagonNumberId, wagonNumberId)
                        .orderByDesc(UnloadLog::getCreatedAt));
        if (CollUtil.isNotEmpty(unloadLogList)) {
            return unloadLogList.get(0).getNumber();
        }
        return null;
    }

    //@Async(value = "taskExecutor")
    @Override
    public void saveUnloadLog(UnloadLogWeighParam param, Task task, IcWagonNumberResult icWagonNumber, String number) {
        log.info("===saveUnloadLog=====");
        LambdaQueryWrapper<UnloadLog> query = new LambdaQueryWrapper<>();
        query.eq(UnloadLog::getTaskId, task.getId());
        query.eq(UnloadLog::getWagonNumberId, icWagonNumber.getWagonNumberId());
        query.eq(UnloadLog::getMaterialId, task.getMaterialId());
        query.eq(UnloadLog::getLoadId, task.getLoadId());
        query.eq(UnloadLog::getUnloadId, task.getUnloadId());
        query.orderByDesc(UnloadLog::getId);
        List<UnloadLog> unloadLogList = unloadLogMapper.selectList(query);
        UnloadLog unloadLog = new UnloadLog();
        if (CollUtil.isEmpty(unloadLogList)) {
            unloadLog = new UnloadLog();
            unloadLog.setIcId(icWagonNumber.getId());
            unloadLog.setLoadId(task.getLoadId());
            unloadLog.setUnloadId(task.getUnloadId());
            unloadLog.setWagonNumberId(icWagonNumber.getWagonNumberId());
            unloadLog.setMaterialId(task.getMaterialId());
            unloadLog.setTare(new BigDecimal(param.getWeight()).divide(new BigDecimal("1000")).toString());
            //unloadLog.setRough(param.getWeight());
            unloadLog.setRoughImg(param.getImg1());
            unloadLog.setRoughImgTwo(param.getImg2());
            unloadLog.setNumber(number);
            unloadLog.setTaskId(task.getId());
            saveOrUpdate(unloadLog);
        } else {
            unloadLog = unloadLogList.get(0);
            unloadLog.setIcId(icWagonNumber.getId());
            unloadLog.setLoadId(task.getLoadId());
            unloadLog.setUnloadId(task.getUnloadId());
            unloadLog.setWagonNumberId(icWagonNumber.getWagonNumberId());
            unloadLog.setMaterialId(task.getMaterialId());
            //unloadLog.setTare(icWagonNumber.getTare());
            unloadLog.setRough(new BigDecimal(param.getWeight()).divide(new BigDecimal("1000")).toString());
            unloadLog.setRoughImg(param.getImg1());
            unloadLog.setRoughImgTwo(param.getImg2());
            unloadLog.setNumber(number);
            unloadLog.setTaskId(task.getId());
            saveOrUpdate(unloadLog);
        }

    }

    /**
     * 查询条件
     *
     * @param param
     * @return
     */
    private QueryWrapper<UnloadLogListResult> queryFilter(UnloadLogListParam param) {
        QueryWrapper<UnloadLogListResult> queryWrapper = new QueryWrapper();
        //查询时间
        queryWrapper.ge("iul.created_at", param.getStartDate());
        queryWrapper.le("iul.created_at", param.getEndDate());
        //查物料名称
        if (StringUtils.isNotBlank(param.getMaterialName()))
            queryWrapper.like("im.name", param.getMaterialName());
        //查车牌号
        if (StringUtils.isNotBlank(param.getVehNumber()))
            queryWrapper.like("iwn.number", param.getVehNumber());
        //查地榜单号
        if (StringUtils.isNotBlank(param.getNumber()))
            queryWrapper.like("iul.number", param.getNumber());
        //查装货地点
        if (StringUtils.isNotBlank(param.getLoadName()))
            queryWrapper.like("igl.name", param.getLoadName());
        //查卸货地点
        if (StringUtils.isNotBlank(param.getUnloadName()))
            queryWrapper.like("igl2.name", param.getUnloadName());
        //按时间倒叙
        queryWrapper.orderByDesc("iul.created_at");
        return queryWrapper;
    }
}